/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package utils;

import com.sun.xml.bind.v2.runtime.IllegalAnnotationException;
import java.io.File;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author kenisk
 */
public class JAXBUtil {
     public static void marshal(String filePath, Object obj) {
        try {
            JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar.marshal(obj, new File(filePath));
        }catch (IllegalAnnotationException ex){

        }
        catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    public static void  marshal(OutputStream ouput, Object obj){
        try {
            JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar.marshal(obj,ouput);
        }catch (IllegalAnnotationException ex){

        }
        catch (JAXBException e) {
            e.printStackTrace();
        }
    }
    public static Object unmarshal(String packagePath, String filePath) {
        try {
            JAXBContext jc = JAXBContext.newInstance(packagePath);
            Unmarshaller u = jc.createUnmarshaller();
            File f = new File(filePath);
            Object item = (Object) u.unmarshal(f);
            return item;
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }


}
